<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center></el-alert>
      <el-steps :active="activeStep-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addForm" :rules="addFormRul" ref="addFormRef" label-position="top">
        <el-tabs
          tab-position="left"
          v-model="activeStep"
          :before-leave="beforLeave"
          @tab-click="clickTabs"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number " type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
                clearable
                expandTrigger="hover"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 复选框 -->
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
              width="0"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item1" v-for="(item1,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
              width="0"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 提交添加商品的按钮 -->
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="预览图片" :visible.sync="PicdialogVisible">
      <img :src="prviewPicUrl" alt width="100%" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeStep: '0',
      //   添加商品的信息
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 1,
        // 商品所属的分类数组
        goods_cat: [],
        // 图片数组
        pics: [],
        // 商品描述
        goods_introduce: '',
        attrs: []
      },
      //   获取到的商品分类信息
      cateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   级联选择器双向绑定的数组
      selectedKeys: [],
      addFormRul: {
        goods_name: [{ required: true, message: '不可为空', trigger: 'blur' }],
        goods_price: [{ required: true, message: '不可为空', trigger: 'blur' }],
        goods_weight: [
          { required: true, message: '不可为空', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '不可为空', trigger: 'blur' }
        ],
        goods_cat: [{ required: true, message: '不可为空', trigger: 'blur' }]
      },
      //  动态参数列表
      manyTableData: [],
      // 静态参数列表
      onlyTableData: [],
      //  多选框选择数据
      checkList: [],
      // 请求头数据对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览对话框的显示与隐藏
      PicdialogVisible: false,
      // 图片预览的路径
      prviewPicUrl: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    setActiveStep(e) {
      //   if (this.addForm.goods_cat.length !== 3) {
      //     return false
      //   }
      // Number("")，将传入的参数转换成数字格式
      this.activeStep = Number(e.index)
      console.log(this.activeStep)
    },
    // 获取商品分类
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
    },
    // 级联选择器的选中项发生变化时就会触发
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 在标签切换之前触发这个函数
    beforLeave(activeName, oldActiveName) {
      //   判断当前处于第几个标签 并且是否选中了三级分类
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    // 点击标签时发起请求
    async clickTabs() {
      if (this.activeStep === '1') {
        const {
          data: res
        } = await this.$http.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          { params: { sel: 'many' } }
        )
        // 将字符串分割成数组，（先判断attr_vals是否为空）
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0
              ? []
              : (item.attr_vals = item.attr_vals.split(','))
        })
        this.manyTableData = res.data
      } else if (this.activeStep === '2') {
        const {
          data: res
        } = await this.$http.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          { params: { sel: 'only' } }
        )
        // 将字符串分割成数组，（先判断attr_vals是否为空）
        // res.data.forEach(item => {
        //   item.attr_vals =
        //     item.attr_vals.length === 0
        //       ? []
        //       : (item.attr_vals = item.attr_vals.split(','))
        // })
        this.onlyTableData = res.data
      }
    },
    // 图片预览效果的处理函数
    handlePreview(file) {
      console.log(file)
      this.PicdialogVisible = true
      this.prviewPicUrl = file.response.data.url
    },
    // 移除图片的处理函数
    handleRemove(file) {
      // 获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 从pics数组中找到这个图片对应的索引值
      const index = this.addForm.pics.findIndex(item => item.pic === filePath)
      // 调用splice方法，把图片对象从pics中移除
      this.addForm.pics.splice(index, 1)
    },
    // 文件上传成功时的函数
    handleSuccess(res) {
      // 使用解构赋值得到图片信息对象
      const picsInfo = { pic: res.data.tmp_path }
      // 将图片信息对象push到pics数组中
      this.addForm.pics.push(picsInfo)
    },
    // 添加商品的处理函数
    addGoods() {
      this.$refs.addFormRef.validate(async v => {
        if (!v) {
          return this.$message.error('请检查必填项！')
        }
        // 执行添加的业务逻辑
        // 使用lodash 进行数据的深拷贝，解决双向绑定的数据错误问题
        const form = _.cloneDeep(this.addForm)
        // 将 goods_cat数组拼接成字符串
        form.goods_cat = this.addForm.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        // 将原数据中的attrs赋值给深拷贝的attrs
        form.attrs = this.addForm.attrs
        // 发起请求添加商品
        const { data: res } = await this.$http.post('/goods', form)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加新商品失败！')
        }
        // 通过编程式导航跳转至商品列表页面
        this.$router.push('/goods')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.addBtn {
  margin-top: 15px;
}
</style>
